<template>
  <div id="register">
    <header>
      <p>注册</p>
    </header>
    <main>
      <div class="form">
        <van-form validate-first @failed="onFailed" submit-on-enter>
          <!-- 通过 pattern 进行正则校验 -->
          <van-field label="用户名：" required
            v-model="user.userName"
            placeholder="请输入用户名"
            :rules="[{message: '请输入用户名' }]"
          />
          <van-field maxlength="11" label="手机号：" required
          v-model="user.phone"
          name="pattern"
          placeholder="请输入手机号"
          :rules="[{ pattern, message: '请输入正确手机号' }]"
        />
          <van-field minlength="6" label="密码：" required
          v-model="user.password"
          name="validator"
          placeholder="请输入密码"
          :rules="[{ validator, message: '密码不少于6位' }]"
        />
      
          <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit" @click="submit">注册</van-button>
          </div>
        </van-form>
      </div>
    </main>
  </div>
</template>

<script>
import Vue from 'vue';
import { Form, Toast } from 'vant';
import { Field } from 'vant';
import axios from 'axios';


Vue.use(Form);
Vue.use(Field)
  export default {
    data() {
    return {
      user:{
        userName:'',
        phone: '',
        password: '',
      },
      pattern: /^1[3-9]\d{9}$/,
      
    };
  },
  methods: {
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(password) {
      return /^\d{6}$/.test(password);
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    async submit(){
      // console.log(this.phone,this.password,this.userName);
      let res = await axios({
        url:'http://192.168.20.106:8000/api/register',
        method:'post',
        data:{
          name:this.user.userName,
          phone: this.user.phone,
          password: this.user.password,
        }
      })
      // console.log(res,'222');
      if(res.data.code==200){
        this.$router.push({path:'/login'})
        this.$store.commit('SET_USER',res.data)
      }else{
        Toast('账号密码错误')
      }
    }
  },
  // mounted(){
  //   console.log(this.$store.state);
  // }
  }
</script>

<style scoped lang="scss">
.login{
  width: 100%;
  height: 100%;
  background: #0bc1d5;
}
header{
  width: 100%;
  height: 100px;
  background: #0bc1d5;
  position: absolute;
  left: 0;
  top: 0;
  margin-bottom: 10px;
  p{
    font-size:30px;
    color: #333;
    text-align: center;
  }
}
main{
  padding-top:100px;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  background: #f2f2f2;
  .form{
    margin: 10px;
    
  }
}
</style>